let util = require('../../utils/util.js');
let app = getApp();

Page({

  data: {
    isFocus: false,
    search_movies: []
  },

  onLoad: function(options) {
    let baseurl = app.globalData.request_baseUrl;
    // 正在热映
    let in_theaters = baseurl + '/v2/movie/in_theaters?start=0&count=3';
    // 即将上映
    let coming_soon = baseurl + '/v2/movie/coming_soon?start=0&count=3';
    // Top250
    let top250 = baseurl + '/v2/movie/top250?start=0&count=3';
    this.getMovieList(in_theaters, (data) => {
      this.setData({
        in_theaters: {
          movies: data,
          typeTitle: "正在热映"
        }
      });
    });
    this.getMovieList(coming_soon, (data) => {
      this.setData({
        coming_soon: {
          movies: data,
          typeTitle: "即将上映"
        }
      });
    });
    this.getMovieList(top250, (data) => {
      this.setData({
        top250: {
          movies: data,
          typeTitle: "豆瓣Top250"
        }
      });
    });
  },
  // 获取电影列表
  getMovieList(url, callback) {
    util.http(url, (data) => {
      callback(this.transformData(data.subjects));
    })
  },

  // 转换数据
  transformData(arr) {
    return arr.map((item) => {
      return {
        id: item.id,
        image_url: item.images.large,
        name: item.title,
        // 分数
        score: item.rating.average,
        // 星星
        stars: +item.rating.stars.slice(0, 1)
      }
    })
  },
  // 跳转更多页面
  onMoreTap(e) {
    wx.navigateTo({
      url: 'more-movie/more-movie?type=' + e.currentTarget.dataset.type,
    })
  },
  // 获取聚焦
  onFocus() {
    this.setData({
      isFocus: true
    });
  },
  // 确认完成 
  onConfirm(e) {
    let val = e.detail.value;
    let baseurl = app.globalData.request_baseUrl;
    let url = baseurl + '/v2/movie/search?q=' + val;
    this.getMovieList(url, (data) => {
      console.log(data);
      this.setData({
        search_movies:  data
      });
    });
  },
  // 关闭
  onClose() {
    this.setData({
      isFocus: false
    });
  }
})